<template>
    <xh-pages navBarText="情侣聊天室" :navLeftText="isBack ? '返回' : '分手'" navBgColor="#FF6997" @hanldClickLeft="hanldClickLeft">
        <view class="pages-container">
            <view class="chat-system">
                <view class="title">
                    <view class="chat-title">话题</view>
                    <view class="time">
                        剩余时间：
                        <u-count-down :time="detail.expire_second * 1000" format="HH:mm:ss" @finish="hanldFinish"
                            v-if="detail.expire_second" />
                        <text v-else>无时长</text>
                    </view>
                </view>
                <view class="content">{{ detail.subject_content }}</view>
            </view>
            <scroll-view class="chat-container" :scroll-y="true" :scroll-into-view="scrollId">
                <view class="item chat-target"
                    :class="{ 'chat-target': item.type === '10', 'chat-wode': item.type === '20' }"
                    v-for="(item, index) in datalist" :key="index" :id="`target${index}`">
                    <image class="avatar"
                        :src="siteInfo.match_home_man ? siteInfo.match_home_man : '/static/pic_boy@2x.png'"
                        v-if="item.queue.role_type === '10'" />
                    <image class="avatar"
                        :src="siteInfo.match_home_woman ? siteInfo.match_home_woman : '/static/pic_girl@2x.png'"
                        v-if="item.queue.role_type === '20'" />
                    <view class="content">
                        <!-- 图片 -->
                        <image class="image" mode="aspectFill" :src="item.content" v-if="item.msg_type === '20'"
                            @tap="hanldPreview(item.content)" />
                        <!-- 表情 -->
                        <image class="emote" mode="aspectFill" :src="showEmote(item.content)"
                            v-else-if="item.msg_type === '40'" />
                        <!-- 文字 -->
                        <view class="message" v-else>
                            {{ item.content }}
                        </view>
                    </view>
                </view>
            </scroll-view>
            <view class="chat-action-group" v-if="!isBack">
                <input type="text" placeholder="你想和我聊点什么呢？" v-model="message" class="message" />
                <view class="action-group">
                    <!-- 上传图片 -->
                    <u-icon name="photo" size="26" color="#333333" @tap="hanldPictuer" />
                    <!-- 打开表情库 -->
                    <u-icon name="/static/emote.png" size="24" color="#333333" @tap="emoteModal.show = true" />
                    <!-- 发送文字 -->
                    <view class="submit" @tap="hanldSubmit">发送</view>
                </view>
            </view>
            <!-- 表情库 -->
            <u-popup v-bind="emoteModal" @close="closeEmoteModal">
                <view class="emote-content">
                    <view class="item" v-for="(item, index) in 109" :key="index" @tap="hanldClickEmote(item)">
                        <image class="emote" :src="`/static/emote/emo_${item}.png`" />
                    </view>
                </view>
            </u-popup>
        </view>
    </xh-pages>
</template>

<script setup lang="ts">
import type { MessageTypes } from '@/common/types/MessageTypes'
import { upload } from '@/common/upload';
import config from '@/common/config';
import { useSite } from '@/stores/site';
import { useUserStore } from '@/stores/user';
import { toast } from '@/utils/helpers'

// 是否允许VIP返回
const isBack = ref(false)
const fenshou = ref(false)

// 滚动ID
const scrollId = ref('')

const siteInfo = storeToRefs(useSite()).siteInfo
const userinfo = storeToRefs(useUserStore()).userInfo

// 表情库弹出层
const emoteModal = ref({
    show: false,
    closeOnClickOverlay: true,
})

// 底部高度
const footerHeightVar = computed(() => isBack.value ? '0px' : '100px')

const detail = ref<{
    id: number | string
    subject_content: number | string
    expire_second: number
}>({
    id: '',
    subject_content: '',
    expire_second: 0,
})
const datalist = ref<MessageTypes[]>([])
const message = ref('')

// 分手
const handleBreakUp = () => {
    fenshou.value = true;
    const data = {
        room_id: detail.value.id
    }
    uni.$u.http.post('Matchs/breakUp', data).then((res: any) => {
        toast(res?.msg ?? '网络错误')
        if (res?.code == 200) {
            setTimeout(() => {
                uni.navigateBack();
            }, 1500);
        }
    })
}

// 倒计时结束
const hanldFinish = (e: any) => {
    uni.showModal({
        title: "温馨提示",
        content: "您与该对象的聊天结束，可开通会员继续聊天",
        showCancel: false,
        success: (res) => {
            uni.reLaunch({ 'url': '/pages/users/index?t=1' })
        }
    })
}

const hanldClickLeft = () => {
    if (isBack.value) {
        uni.navigateBack();
        return;
    }
    uni.showModal({
        title: "温馨提示",
        content: "是否确认与该对象分手？",
        success: (res) => {
            if (res.confirm) {
                handleBreakUp()
            }
        }
    })
}

// 替换显示表情包
const showEmote = (emo: string) => {
    const emote = emo.replace(/\[emo:(\d+)\]/g, (match, p1) => {
        return config.baseUrl + `static/emote/emo_${p1}.png`;
    })
    return emote
}

// 发送表情包
const hanldClickEmote = (emote: string | number) => {
    const emo = `[emo:${emote}]`
    sendMessage(emo, '40')
    emoteModal.value.show = false
}

// 关闭表情库
const closeEmoteModal = () => {
    emoteModal.value.show = false
}

// 图片预览
const hanldPreview = (url: string) => {
    uni.previewImage({
        urls: [url]
    })
}

// 发送图片
const hanldPictuer = () => {
    uni.chooseImage({
        count: 9,
        success: (res) => {
            const tempFilePaths = res.tempFilePaths as string[]
            tempFilePaths.forEach((path) => {
                upload(path, 'emote').then((url) => {
                    sendMessage(url, '20')
                })
            })
        }
    })
}

const getRoomDetail = () => {
    const params = {
        room_id: detail.value.id
    }
    uni.$u.http.get('Room/detail', { params }).then((res: any) => {
        detail.value = res?.data
    })
}
// 发送消息请求体
const sendMessage = (msg: string, type = '10') => {
    const params = {
        room_id: detail.value.id,
        msg_type: type,
        content: msg
    }
    uni.$u.http.post('Chat/message', params).then((res: any) => {
        if (res?.code == 200) {
            message.value = ''
        }
    })
}
// 点击发送按钮
const hanldSubmit = () => {
    sendMessage(message.value)
}
const continueChat=ref(false);
const getMessage = () => {
    const params = {
        room_id: detail.value.id
    }
    uni.$u.http.get('Chat/index', { params }).then((res: any) => {
        datalist.value = [];
        const data: MessageTypes[] = res?.data?.data ?? []
        data.forEach((item) => {
            datalist.value.unshift(item);
        })
        nextTick(() => {
            scrollId.value = `target${data.length - 1}`
        })
        // 已分手
        if (res?.data?.isClose && !isBack.value) {
            fenshou.value = true
            uni.showModal({
                title: "温馨提示",
                content: "聊天已结束",
                showCancel: false,
                success: (res) => {
                    uni.reLaunch({ 'url': '/pages/index/index' })
                }
            })
            return;
        }
        if (res?.data?.isOffline && !isBack.value && !continueChat.value) {
            fenshou.value = true
            uni.showModal({
                title: "温馨提示",
                content: "对方似乎已离线，是否继续聊天？",
                confirmText: '继续聊天',
                cancelText: '分手',
                success: (res) => {
                    if (res.confirm) {
                        fenshou.value = false;
                        continueChat.value=true;
                        setTimeout(() => {
                            getMessage();
                        }, 1000);
                    } else {
                        handleBreakUp()
                    }
                }
            })
            return;
        }

        if (!fenshou.value && !isBack.value) {
            setTimeout(() => {
                getMessage();
            }, 1000);
        }
    })
}

const initify = async () => {
    await getRoomDetail()
    await getMessage()
}

onLoad((option: any) => {
    detail.value.id = option?.room_id ?? ''
    isBack.value = option?.isBack ? true : false
    initify();
})
</script>

<style lang="scss" scoped>
.pages-container {
    padding-bottom: 100rpx;

    .chat-system {
        background-color: #fff;
        height: 50px;
        padding: 20rpx;

        .title {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .title-text {
                font-size: 32rpx;
                font-weight: 700;
            }

            .time {
                font-size: 26rpx;
                display: flex;
                align-items: center;
                gap: 6rpx;
            }
        }

        .content {
            font-size: 26rpx;
            color: #333;
            margin-top: 20rpx;
        }
    }

    .chat-container {
        height: calc(100vh - v-bind(footerHeightVar) - 44px - 70px);

        .item {
            padding: 0 20rpx;
            margin: 40rpx 0;
            display: flex;
            gap: 15rpx;

            .avatar {
                width: 90rpx;
                height: 90rpx;
                border-radius: 50%;
                display: block;
            }

            .content {
                .message {
                    background-color: #fff;
                    padding: 20rpx 30rpx;
                    font-size: 26rpx;
                    color: #333;
                }

                .image {
                    width: 200rpx;
                    height: 200rpx;
                }

                .emote {
                    width: 80rpx;
                    height: 80rpx;
                }
            }
        }

        .chat-target {}

        .chat-wode {
            flex-flow: row-reverse;
        }
    }

    .chat-action-group {
        display: flex;
        align-items: center;
        background: #fff;
        height: 100rpx;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 0 20rpx;

        .message {
            flex: 1;
            font-size: 28rpx;
        }

        .action-group {
            display: flex;
            gap: 15rpx;

            .submit {
                background-color: #FF6997;
                color: #fff;
                padding: 15rpx 30rpx;
                border-radius: 20rpx;
            }
        }
    }
}

.emote-content {
    height: 400rpx;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    gap: 30rpx;
    padding: 30rpx 20rpx;

    .item {
        .emote {
            width: 60rpx;
            height: 60rpx;
        }
    }
}</style>